<template>
<div class="page-appbuy">
  <el-form label-position="top" :rules="rules" ref="ruleForm" :model="form">
    <div class="title">
      填写回购基本信息
    </div>
    <div class="buy-item">
      <div class="buy-row">
        <el-form-item label="仓库" prop="storageId">
          <el-select v-model="form.storageId"   filterable   placeholder="选择仓库" @change="getSellArOption">
            <el-option v-for="item in storageOption" :key="item.id" :label="item.storageName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对象" prop="buyerId" >
          <el-select v-model="form.buyerId"  filterable   placeholder="选择交易对象" @change="getSellArOption">
            <el-option v-for="item in buyerOption" :key="item.buyerId" :label="item.buyerName" :value="item.buyerId"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="buy-row">
        <el-form-item label="出售申请编号" prop="sellArId">
          <el-select v-model="form.sellArId" placeholder="选择出售申请编号" filterable  :clearable="clearable" @change="getTableData">
            <el-option v-for="item in arNoOption" :key="item.id" :label="item.arNo" :value="item.id">
              <div class="buy-row-define">
                <span>编号: {{item.arNo}}&nbsp;</span>
                <span :title="item.goodsNames">货物名称: {{item.goodsNames}}&nbsp;</span>
                <span >货物总重量: <span v-if="item.totalWeight !== null">{{item.totalWeight}}&nbsp;</span></span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </div>
  </el-form>
  <div class="appbuy-box" v-if="tableData.length > 0">
    <div class="appbuy-title">选择要回购的货物</div>
    <el-table :data="tableData" :span-method="objectSpanMethod" @selection-change="handleSelectionChange" border style="width: 100%;">
      <el-table-column align="center" type="selection" width="40"></el-table-column>
      <el-table-column align="center" prop="busNo" label="仓单业务号" width="160"></el-table-column>
      <el-table-column align="center" prop="goodsName" label="货物名称" width="180"></el-table-column>
      <el-table-column align="center" prop="cntrNo" label="柜号" width="160"></el-table-column>
      <el-table-column align="center" prop="vendor" label="生产厂家" width="100"></el-table-column>
      <el-table-column align="center" prop="countryOrigin" label="原产地" width="120"></el-table-column>
      <el-table-column align="center" prop="packageDesc" label="包装" width="80"></el-table-column>
      <el-table-column align="center" prop="productDate" label="生产日期" width="140"></el-table-column>
      <el-table-column align="center" prop="sellNum" label="出售数量" width="120"></el-table-column>
      <el-table-column align="center" prop="wsLeftNum" label="待回购数量" width="120"></el-table-column>
      <el-table-column align="center" prop="unitDesc" label="单位" width="100"></el-table-column>
      <el-table-column align="center" prop="repurchaseNum" label="回购数量" width="180" fixed="right">
        <template slot-scope="scope">
          <el-input v-model="scope.row.repurchaseNum" placeholder="请输入回购数量"  maxlength="10" @blur="checkSellNum(scope.$index,scope.row.wsLeftNum,scope.row.repurchaseNum)" :disabled="!scope.row.selected"></el-input>
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="wrId" label="对应仓单" width="120">
        <template slot-scope="scope">
          <el-button type="primary" plain @click="toDetail(scope.$index, scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="submit-btn-box" v-if="tableData.length > 0">
    <a class="ml-btn-default w140" @click="toPreview">预览</a>
  </div>
  <pc-dialog :is-show="isAppBuyPre"  title ='回购预览' @on-close="isAppBuyPre = false">
    <div >
      <AppBuyPView :previewData="previewData" :form="form" @closeRefresh="closeRefresh"></AppBuyPView>
    </div>
  </pc-dialog>
  <pc-dialog :is-show="isBillDetail"  title ='仓单详情' @on-close="isBillDetail = false">
    <div >
      <bill-detail :id="storageId"></bill-detail>
    </div>
  </pc-dialog>
</div>
</template>
<script>
import PcDialog from 'components/dialog';
import AppBuyPView from 'src/views/wms/trade/buy-back/appBuyPView';
import BillDetail from 'src/views/wms/dataquery/billlist/billManagement/billDetail';
export default{
  created () {
    this.rowspan();// 测试用
    this.getStorageOptionData();// 获取仓库Option数据
    this.getBuyerOptionData(); // 获取交易对象Option数据
  },
  components: {
    PcDialog, AppBuyPView, BillDetail
  },
  data () {
    return {
      form: {
        arType: 2,
        sellArId: null, // 出售申请编号
        storageId: null, // 仓库id
        storageName: '',
        buyerId: null // 交易对象 id
      },
      clearable: true,
      isAppBuyPre: false,
      tableData: [],
      isBillDetail: false,
      spanArr: [],
      position: 0,
      storageOption: [],
      arNoOption: [], // 出售申请编号
      buyerOption: [],
      previewData: [],
      storageId: null,
      rules: {
        // buyerId repurchaseDays
        storageId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        buyerId: [
          { required: true, message: '请选择交易对象', trigger: 'change' }
        ],
        sellArId: [
          { required: true, message: '请选择出售申请编号', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    toPreview () {
      let valid = this.checkCondition();
      if (valid) {
        this.previewData = this.PreData();
        for (var i = 0; i < this.previewData.length; i++) {
          this.previewData[i].referWeight = this.previewData[i].refAvgWeight * this.previewData[i].repurchaseNum;
          this.previewData[i].referWeight = Number(this.previewData[i].referWeight).toFixed(2);
          this.previewData[i].repurchaseNum = Number(this.previewData[i].repurchaseNum);
        }
        this.isAppBuyPre = true;
      }
    },
    // 根据仓库id获取货物列表信息
    getTableData () {
      let that = this;
      if (!that.form.sellArId) {
        this.tableData = [];
        return;
      }
      that.ajax({
        url: '/maliwms/ar/getRepurchaseWrGoodsList?sellArId=' + that.form.sellArId,
        type: 'GET',
        loading: false,
        success: (res) => {
          setTimeout(() => {
            that.$pcNProgress.done();
          }, 300);
          if (res.code === 200) {
            this.tableData = res.result;
            this.rowspan();
          }
        }
      });
    },
    getSellArOption () {
      this.form.sellArId = null;
      if (this.form.storageId === null || this.form.storageId === '' || this.form.buyerId === null || this.form.buyerId === '') {
        this.arNoOption = [];
        this.form.sellArId = null;
        return false;
      }
      let that = this;
      let params = {};
      params.financingCompany = this.form.buyerId;
      params.storageId = this.form.storageId;
      that.ajax({
        url: '/maliwms/ar/getSellArInfoList',
        type: 'POST',
        data: params,
        loading: false,
        success: (res) => {
          setTimeout(() => {
            that.$pcNProgress.done();
          }, 300);
          if (res.code === 200) {
            this.arNoOption = res.result;
          } else {
            this.arNoOption = [];
          }
        }
      });
    },
    // 获取仓库数据
    getStorageOptionData () {
      let that = this;
      that.ajax({
        url: '/maliwms/storage/selectStorage',
        type: 'POST',
        data: {},
        loading: false,
        success: (res) => {
          setTimeout(() => {
            that.$pcNProgress.done();
          }, 300);
          if (res.code === 200) {
            this.storageOption = res.result;
          }
        }
      });
    },
    checkSellNum (index, oldVal, newVal) {},
    toDetail (index, row) {
      this.storageId = row.wrId;
      this.isBillDetail = true;
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 12) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    rowspan () {
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          this.spanArr.push(1);
          this.position = 0;
        } else {
          if (this.tableData[index].wrId === this.tableData[index - 1].wrId) {
            this.spanArr[this.position] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.position = index;
          }
        }
      });
    },
    // 处理回购货物 点击事件
    handleSelectionChange (selection) {
      let tableDataLength = this.tableData.length;
      for (var i = 0; i < tableDataLength; i++) {
        var j = 0;
        for (; j < selection.length; j++) {
          if (selection[j].wrGoodsId === this.tableData[i].wrGoodsId) {
            this.tableData[i].selected = true;
            break;
          }
        }
        if (j === selection.length) {
          this.tableData[i].selected = false;
        }
      }
    },
    // 获取交易对象Option数据
    getBuyerOptionData () {
      let that = this;
      that.ajax({
        url: '/maliwms/ar/getFinancingCompanyInfoListByLoginUser',
        type: 'GET',
        loading: false,
        success: (res) => {
          setTimeout(() => {
            that.$pcNProgress.done();
          }, 300);
          if (res.code === 200) {
            this.buyerOption = res.result;
          } else {
            this.buyerOption = [];
          }
        }
      });
    },
    checkCondition () {
      if (this.form.storageId === '' || this.form.storageId === null) {
        this.errorTip('请选择仓库');
        return false;
      }
      if (this.form.buyerId === '' || this.form.buyerId === null) {
        this.errorTip('请选择交易对象');
        return false;
      }
      if (this.form.sellArId === '' || this.form.sellArId === null) {
        this.errorTip('出售申请编号');
        return false;
      }

      let goodData = this.PreData();
      if (goodData.length === 0) {
        this.errorTip('请选择要回购的货物');
        return false;
      }
      var checkNum = true;
      for (var i = 0; i < goodData.length; i++) {
        if (isNaN(goodData[i].repurchaseNum)) {
          this.errorTip('请输入数字');
          checkNum = false;
          break;
        }
        if (goodData[i].repurchaseNum === '0') {
          this.errorTip('回购数量需要大于0');
          checkNum = false;
          break;
        }
        if (goodData[i].repurchaseNum === null || goodData[i].repurchaseNum === '') {
          this.errorTip('回购数量不能为空');
          checkNum = false;
          break;
        }
        if (Number(goodData[i].repurchaseNum) > Number(goodData[i].wsLeftNum)) {
          this.errorTip('回购数量不能大于待回购数量');
          checkNum = false;
          break;
        }
      }
      if (!checkNum) {
        return false;
      }
      if (!checkNum) {
        return false;
      }
      return checkNum;
    },
    PreData () {
      let tempData = [];
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].selected) {
          tempData.push(this.tableData[i]);
        }
      }

      if (this.storageOption.length > 0) {
        for (var j = 0; j < this.storageOption.length; j++) {
          if (this.form.storageId === this.storageOption[j].id) {
            this.form.storageName = this.storageOption[j].storageName;
          }
        }
      }
      if (this.buyerOption.length > 0) {
        for (var k = 0; k < this.buyerOption.length; k++) {
          if (this.form.buyerId === this.buyerOption[k].buyerId) {
            this.form.buyerName = this.buyerOption[k].buyerName;
          }
        }
      }
      return tempData;
    },
    closeRefresh () {
      this.isAppBuyPre = false;
      this.$emit('closeRefresh', 'appBuy');
    }
  }
};
</script>
<style>
.page-appbuy .el-form{
  height: 100%;
  border: 1px solid #e5e5e5;
  background: #fff;
  padding-bottom: 30px;
}
.page-appbuy .title{
  font-size:16px;
  color:#333333;
  border-bottom:1px solid #e5e5e5;
  background:#fff;
  height: 50px;
  line-height:50px;
  padding-left:20px;
  margin-bottom:20px;
}
.page-appbuy .buy-item .el-form-item{
  width:45.7%;
  display:inline-block;
  margin-left:2.6%
}
.page-appbuy .buy-item .el-input--small{
  width:100%;
  display:inline-block;
}
.page-appbuy .el-select.el-select--small{
  width:100%;
}
.page-appbuy .el-form-item__label {
  padding-bottom: 0;
  font-size: 14px;
}
.page-appbuy .el-form-item--small.el-form-item {
  margin-bottom: 12px;
}
.page-appbuy .appbuy-title{
  font-size:16px;
  color:#333333;
  border:1px solid #ebeef5;
  background:#fff;
  height: 50px;
  line-height:50px;
  padding-left:20px;
  margin-top:26px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  margin-bottom:-1px;
}
.page-appbuy .ml-btn-default, .ml-btn-default:hover {
  min-width: 140px;
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  margin: 0 5px;
  background-color: #1383f2;
  border-radius: 2px;
  color: #fff;
  font-size: 16px;
  text-align: center;
  display: inline-block;
  text-decoration: none;
  outline: none;
  cursor: pointer;
  border: none;
  position: relative;
  z-index: 10;
}
.page-appbuy .submit-btn-box{
  text-align:center;
  margin-top:50px;
}
.page-appbuy .el-table tr th:first-child .cell .el-checkbox{
  display:none;
}
.page-appbuy .el-input.el-input--small.is-disabled{
  display:none;
}
.page-appbuy .el-table--enable-row-transition .el-table__body td{
  line-height:49px;
  height:49px;
}
.buy-row-define{
  display: flex;
  justify-content: space-between;
  width:400px;
}
.buy-row-define>span{
  width:30%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.page-appsale .ml-btn-default{
    margin-bottom:50px;
}
.el-form-item.must label {
  position: relative;
  padding-left: 7px;
}
.el-form-item.must label:before{
  position:absolute;
  content:'*';
  color: #f56c6c;
  top:0;
  left:0;
}
</style>
